/**
 * 选择组织机构和凭证字界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.Voucher.SelectOrgAndWordForm", {
  extend: "PSI.AFX.Form.EditForm",

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;

    // 组织机构
    const modelName = me.buildModelName(me, "Org");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    // 凭证字
    const modelNameWord = me.buildModelName(me, "VoucherWord");
    PCL.define(modelNameWord, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    const buttons = [{
      id: me.buildId(me, "buttonOK"),
      text: "确定",
      ...PSI.Const.BTN_STYLE,
      formBind: true,
      iconCls: "PSI-button-ok",
      handler() {
        me._onOK();
      },
      scope: me
    }, {
      text: "取消",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.close();
      },
      scope: me
    }];

    const logoHtml = me.genLogoHtml(null, "新建凭证 - 选择组织机构和凭证字");

    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      width: 560,
      height: 300,
      layout: "border",
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      },
      items: [{
        region: "north",
        height: 70,
        border: 0,
        html: logoHtml
      }, {
        region: "center",
        border: 0,
        xtype: "form",
        layout: {
          type: "table",
          columns: 1,
          tableAttrs: PSI.Const.TABLE_LAYOUT,
        },
        height: "100%",
        bodyPadding: 5,
        defaultType: 'textfield',
        fieldDefaults: {
          labelWidth: 85,
          labelAlign: "right",
          labelSeparator: "",
          msgTarget: 'side',
          width: 510,
          margin: "5"
        },
        items: [{
          id: me.buildId(me, "editOrg"),
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "组织机构",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "combobox",
          queryMode: "local",
          editable: false,
          valueField: "id",
          displayField: "name",
          store: PCL.create("PCL.data.Store", {
            model: modelName,
            autoLoad: false,
            data: []
          }),
          listeners: {
            select: {
              fn() {
                me.queryVoucherWord();
              },
              scope: me
            },
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editWord"),
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "凭证字",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "combobox",
          queryMode: "local",
          editable: false,
          valueField: "id",
          displayField: "name",
          store: PCL.create("PCL.data.Store", {
            model: modelNameWord,
            autoLoad: false,
            data: []
          }),
          listeners: {
            specialkey: {
              fn: me._onLastEditSpecialKey,
              scope: me
            }
          }
        }],
        buttons,
      }]
    });

    me.callParent(arguments);

    me.editOrg = PCL.getCmp(me.buildId(me, "editOrg"));
    me.editWord = PCL.getCmp(me.buildId(me, "editWord"));
    me.buttonOK = PCL.getCmp(me.buildId(me, "buttonOK"));

    // AFX
    me.__editorList = [me.editOrg, me.editWord];

    me.queryCompanyList();
  },

  /**
 * @private
 */
  _onLastEditSpecialKey(field, e) {
    const me = this;

    if (e.getKey() == e.ENTER) {
      me.buttonOK.focus();
    }
  },

  /**
   * @private
   */
  _onOK() {
    const me = this;

    const org = me.editOrg.getValue();
    const word = me.editWord.getValue();

    if (!org) {
      me.showInfo("没有选择组织机构");
      return;
    }
    if (!word) {
      me.showInfo("没有选择凭证字");
      return;
    }
    const companyId = org;

    const el = me.getEl();
    el?.mask("正在查询当前会计期间");
    const r = {
      url: me.URL("SLN0002/Voucher/queryCurrentPeriod"),
      params: {
        companyId,
      },
      callback(options, success, response) {
        el?.unmask();
        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            const accYear = parseInt(data.year);
            const accMonth = parseInt(data.month);

            me.close();

            const parentForm = me.getParentForm();
            if (parentForm && parentForm.doAddVoucher) {
              parentForm.doAddVoucher.apply(parentForm, [org, word, accYear, accMonth]);
            }
          } else {
            me.showInfo("还没有初始化会计期间，无法新建记账凭证", () => {
              me.editOrg.focus();
            });
          }
        } else {
          me.showInfo("网络错误");
        }
      }
    };
    me.ajax(r);

  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;
    PSI.Const.msgBoxShowing = false;
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    PSI.Const.msgBoxShowing = true;

    me.editOrg.focus();
  },

  /**
   * @private
   */
  queryCompanyList() {
    const me = this;
    const store = me.editOrg.getStore();
    const r = {
      url: me.URL("SLN0002/Voucher/companyList"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            me.editOrg.setValue(data[0]["id"]);
          }

          me.queryVoucherWord();
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  queryVoucherWord() {
    const me = this;
    const store = me.editWord.getStore();
    const r = {
      url: me.URL("SLN0002/Voucher/queryVoucherWord"),
      params: {
        orgId: me.editOrg.getValue(),
      },
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            me.editWord.setValue(data[0]["id"]);
          }
        }
      }
    };
    me.ajax(r);
  },
});
